package com.gdit.zax.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gdit.zax.dao.FindPwdDao;
import com.gdit.zax.dao.UserDao;
import com.gdit.zax.entitys.FindPwd;
import com.gdit.zax.entitys.UserInfo;
import com.gdit.zax.factory.DAOFactory;
import com.gdit.zax.utils.DBUtil;
import com.gdit.zax.utils.EmailUtil;
import com.gdit.zax.utils.MD5;
import com.gdit.zax.utils.O;
import com.gdit.zax.utils.TextUtil;
import com.gdit.zax.utils.VeriFicUtil;

/**
 * 找回密码
 * @author lenovo
 *
 */
public class FindPwdByEmail extends HttpServlet {
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String username = request.getParameter("username");
		String email = request.getParameter("email");
		
		//检测参数
		if (TextUtil.isEmpty(username)) {
			O.printFail(response, 1, "请检查usernam参数!");
			return;
		}
		if (TextUtil.isEmpty(email)) {
			O.printFail(response, 1, "请检查email参数!");
			return;
		}
		
		//检测连接、用户
		Connection conn = DBUtil.getConnection();
		if (conn==null) {
			O.printFail(response, 1000, "数据库连接失败!");
			return;
		}
		
		//开始
		DAOFactory dao = DAOFactory.init(conn, request, response);
		UserDao udao = dao.getUserDao();
		FindPwdDao fdao  =dao.getFindPwdDao();
		
		UserInfo uinfo = udao.getInfobyEmail(username, email);
		if (uinfo==null) {
			O.printFail(response, 1, "用户没有绑定该邮箱!");
			return;
		}
		
		String captche = "" + (int)(Math.random()*900000+100000);
		String changeflag = MD5.getMD5("0," + (int)(Math.random()*900000+100000) + "," +  System.currentTimeMillis());
		 
		FindPwd data = new FindPwd();
		data.setType(0);
		data.setChangeflag(changeflag);
		data.setUserid(uinfo.getId());
		data.setUsername(uinfo.getUsername());
		data.setCaptche(captche);//10000-99999
		if (!fdao.addFindPwd(data)){
			O.printFail(response, 1, "数据库出错，请联系管理员,74!");
			return;
		}
		
		

		
		//最后返回json
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("captche", captche);
		map.put("changeflag", changeflag);
		O.printSuccess(response, map);
		
		
		//发送邮件
		EmailUtil.sendEmail(uinfo.getEmail(), "最爱学修改密码验证码", "你的验证码是：" + captche);
		
	}

}
